<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from './stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const activeTab = ref(0)

// 计算属性
const showNavBar = computed(() => {
  return !route.meta.showTabbar && route.name !== 'Login'
})

const showTabbar = computed(() => {
  return route.meta.showTabbar === true
})

const pageTitle = computed(() => {
  return (route.meta.title as string) || '喵趣AI'
})

// 导航回退
const onNavBack = () => {
  if (window.history.length > 1) {
    router.go(-1)
  } else {
    router.push('/')
  }
}

// 底部导航切换
const onTabChange = (index: number) => {
  const routes = ['/', '/upload', '/history', '/profile']
  router.push(routes[index])
}

// 监听路由变化，更新活跃tab
watch(route, (newRoute) => {
  const tabRoutes = ['/', '/upload', '/history', '/profile']
  const index = tabRoutes.findIndex(path => path === newRoute.path)
  if (index !== -1) {
    activeTab.value = index
  }
}, { immediate: true })

// 初始化用户信息
onMounted(() => {
  userStore.initFromStorage()
})
</script>

<template>
  <div id="app">
    <!-- 导航栏 -->
    <van-nav-bar 
      v-if="showNavBar" 
      :title="pageTitle"
      left-arrow
      @click-left="onNavBack"
      class="nav-bar"
    />
    
    <!-- 主内容 -->
    <div class="main-content" :class="{ 'has-navbar': showNavBar, 'has-tabbar': showTabbar }">
      <router-view v-slot="{ Component }">
        <transition name="page" mode="out-in">
          <component :is="Component" />
        </transition>
      </router-view>
    </div>
    
    <!-- 底部导航 -->
    <van-tabbar 
      v-if="showTabbar" 
      v-model="activeTab" 
      @change="onTabChange"
      class="custom-tabbar"
      active-color="#6366f1"
      inactive-color="#9ca3af"
    >
      <van-tabbar-item icon="home-o" to="/">首页</van-tabbar-item>
      <van-tabbar-item icon="photograph" to="/upload">上传</van-tabbar-item>
      <van-tabbar-item icon="clock-o" to="/history">历史</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<style scoped>
#app {
  height: 100vh;
  background-color: #f7f8fa;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.main-content {
  height: 100vh;
  overflow-y: auto;
}

.main-content.has-navbar {
  padding-top: 46px;
}

.main-content.has-tabbar {
  padding-bottom: 50px;
}

.custom-tabbar {
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

/* 页面切换动画 */
.page-enter-active,
.page-leave-active {
  transition: all 0.3s ease;
}

.page-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.page-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}
</style>
